package com.example.demo.controller;

import com.example.demo.entity.ChapterResource;
import com.example.demo.service.ChapterResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/chapter_resources")
public class ChapterResourceController {

    @Autowired
    private ChapterResourceService service;

    // POST /api/chapter_resources
    // 上传/创建资源记录
    @PostMapping
    public ResponseEntity<?> createResource(@RequestBody ChapterResource resource) {
        try {
            ChapterResource newResource = service.createResource(resource);
            return new ResponseEntity<>(newResource, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage()); // 400 Bad Request
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); // 400 Bad Request
        }
    }

    // GET /api/chapter_resources/chapter/{chapterId}
    // 根据章节 ID 查询所有资源
    @GetMapping("/chapter/{chapterId}")
    public List<ChapterResource> getResourcesByChapterId(@PathVariable("chapterId") Integer chapterId) {
        return service.findResourcesByChapterId(chapterId);
    }

    // GET /api/chapter_resources/{id}
    // 根据资源 ID 查询单个资源
    @GetMapping("/{id}")
    public ResponseEntity<ChapterResource> getResourceById(@PathVariable("id") Integer resourceId) {
        return service.findResourceById(resourceId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build()); // 404 Not Found
    }

    // PUT /api/chapter_resources/{id}
    // 更新资源信息
    @PutMapping("/{id}")
    public ResponseEntity<?> updateResource(@PathVariable("id") Integer resourceId, @RequestBody ChapterResource resourceDetails) {
        resourceDetails.setResourceId(resourceId);

        if (service.updateResource(resourceDetails)) {
            return ResponseEntity.ok("资源信息更新成功");
        } else {
            return ResponseEntity.notFound().build(); // 404 Not Found (原资源不存在)
        }
    }

    // DELETE /api/chapter_resources/{id}
    // 删除资源记录
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteResource(@PathVariable("id") Integer resourceId) {
        if (service.deleteResource(resourceId)) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}